import axios from 'axios'
import QS from 'qs'

var SIGN_REGEXP = /([yMdhsm])(\1*)/g;
var DEFAULT_PATTERN = 'yyyy-MM-dd';
function padding(s, len) {
    var len = len - (s + '').length;
    for (var i = 0; i < len; i++) { s = '0' + s; }
    return s;
};

//axios全局配置
axios.defaults.withCredentials = true
axios.interceptors.request.use(function (config) {
    // 这里的config包含每次请求的内容
    return config;
}, function (err) {
    return Promise.reject(err);
});

//ajax请求
function axiosFn(fn,url,params,loadingFn,sucfn,failFn) {
    if(loadingFn){
        loadingFn(true);
    }
    if(fn==axios.get){
        params = {params}
    }else{
        params = QS.stringify(params)
    }
    return fn(global.serverHost + url,params).then(res => {
        let result = res.data;
        if (result.success) {
            if(loadingFn){
                loadingFn(false);
            }
            if(sucfn){
                sucfn(result);
            }
        } else {
            let _this = global.vueRef;
            if(result && result.code=="600" && _this && _this.$router) {
                //未登录
                _this.$router.push({path: '/login'});
            }
            if(result && result.msg && _this) {
                _this.$message({
                    showClose: true,
                    message: result.code=="202"?"系统错误，请联系管理员":result.msg,
                    type: 'error'
                });
                if(global.debug && result.code=="202") {
                    //global.alert(result.msg)
                    _this.$notify.error({
                        message:result.msg
                    })
                }
            }

            if(loadingFn){
                loadingFn(false);
            }
            if(failFn){
                failFn(result)
            }
        }
        return result;
    }).catch(ex=>{
        console.log("axios.post--->"+url+":"+ex)
        if(loadingFn){
            loadingFn(false);
        }
    });
}

export default {
    //保存表单
    saveForm(url,from,data,loadingFn,sucfn,failFn){
        from.validate(valid=>{
            if(valid) {
                this.post(url, data, loadingFn, result => {
                    //this.msgSuc("保存成功")
                    if(sucfn){
                        sucfn(result)
                    }
                },failFn)
            }else{
                this.msgWarning("填写不符合要求")
            }
        })
    },
    //判断是否有某个角色
    hasRole(roleId){
       return global.roles && global.roles.includes(roleId)
    },
    //判断是否有权限
    /* authName 权限名
       toPath 当前URL
     */
    hasAuth(authName,toPath){
        if (!toPath) {
             toPath = global.nowPath
        }
        //管理员全部有权限
        if(global.user && global.user.FID==-1){
            return true
        }
        for(let item of global.allRoutes){
            //有hidden表示是代码定义的,代码定义的默认都有权限
            if(toPath==item.path && item.hidden!=undefined){
                return true
            }
            if(item.children) {
                //第二层是菜单
                for (let child of item.children) {
                    if(toPath==child.path && child.hidden!=undefined){
                        return true
                    }
                    if(toPath==child.path && authName=="view"){
                          return child.show
                    }
                    if (child.authority) {
                        for (let auth of child.authority) {
                            //componentPath存的是权限名称，path是和父节点的path比较
                            if(toPath==child.path && authName==auth.componentPath){
                                return auth.show
                            }
                        }
                    }
                }
            }
        }
        return false
    },
    //处理权限
    //只在页面初始化和登录时用到
    //TODO:要移除这个文件
    handleAuthority(authority){
        if(!authority){
            return
        }
        //变成map,加快速度
        let map = {}
        for(let item of authority){
            map[item] = true;
        }
        //map[-1] 是管理员
        for(let item of global.allRoutes){
            //初始化成false
            item.show = false
            if(map[-1] || map[item.id``]){
                item.show = true
            }
            if(item.children) {
                //第二层子菜单
                for (let child of item.children) {
                    //初始化成false
                    child.show = false
                    if (map[-1] || map[child.id]) {
                        child.show = true
                        item.show = true
                    }
                    //第三层是权限
                    if (child.authority) {
                        for (let auth of child.authority) {
                            //初始化成false
                            auth.show = false
                            if (map[-1] || map[auth.id]) {
                                auth.show = true
                                child.show = true
                                item.show = true
                            }
                        }
                    }
                }
            }
        }
    },
    //普通消息框
    msg:function (msg) {
        global.vueRef.$message({
            showClose: true,
            message: msg,
            type: 'info'
        });
    },
    //成功消息框
    msgSuc:function (msg) {
        global.vueRef.$message({
            showClose: true,
            message: msg,
            type: 'success'
        });
    },
    //错误消息框
    msgerror:function (msg) {
        global.vueRef.$message({
            showClose: true,
            message: msg,
            type: 'error'
        });
    },
    //警告消息框
    msgWarning:function (msg) {
        global.vueRef.$message({
            showClose: true,
            message: msg,
            type: 'warning'
        });
    },
    //ajax post
    post:function (url,params,loadingFn,sucfn,failFn) {
        return axiosFn(axios.post,url,params,loadingFn,sucfn,failFn);
    },
    //ajax get
    get:function (url,params,loadingFn,sucfn,failFn) {
        return axiosFn(axios.get,url,params,loadingFn,sucfn,failFn);
    },
    //从url中取值
    getQueryStringByName: function (name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
        var r = window.location.search.substr(1).match(reg);
        var context = "";
        if (r != null)
            context = r[2];
        reg = null;
        r = null;
        return context == null || context == "" || context == "undefined" ? "" : context;
    },
    //连接查询条件
    joinWhere:function (...args) {
        let r=""
        args.forEach(arg=>{
            if(arg) {
                if (r) {
                    r += " and "
                }
                r += arg
            }
        })
        return r;
    },
    //有返回值的emit
    //error==true 返回失败false
    //error==字符串，返回失败false，并报错
    //否则返回true
    emit:function (scope,method,...arg) {
        let r = {}
        scope.$emit(method,...arg,r)
        if(r.error){
            if(typeof(r.error)=="string") {
                this.msgWarning(r.error)
            }
            return false;
        }
        return true;
    },
    date: {
        //取当前日期，去掉小时、分钟、秒
        getDate(){
            let d = new Date()
            d.setHours(0)
            d.setMinutes(0)
            d.setSeconds(0)
            d.setMilliseconds(0)
            return d;
        },
        //日期相加天数，add可以是负数
        addDay(date,add){
            date.setTime(date.getTime() + 3600 * 1000 * 24 * add);
        },
        //日期相加月数，add可以是负数，也可以大于12
        addMonth(date,add){
            let m = date.getMonth()
            m += add
            date.setFullYear(date.getFullYear()+parseInt(m/11))
            date.setMonth(m%11)
        },
        //时间格式化对象，把json中的/Date(-62135596800000)/变成日期
        formatObj:function (value,format) {
            if(value) {
                for (let key in value) {
                    //日期变字符，有性能问题吗？
                    if(format && (value[key] instanceof Date)){
                        value[key] = this.format(value[key], format);
                    }else if (value[key] && value[key].toString().substr(0, 6) == "/Date(") {
                        if (value[key] == "/Date(-62135596800000)/") {
                            value[key] = null;
                        }
                        else {
                            if (format) {
                                value[key] = this.format(this.parseToDate(value[key]), format);
                            } else {
                                value[key] = this.parseToDate(value[key]);
                            }
                        }
                    }
                }
            }
            return value;
        },
        //时间格式化数组，把json中的/Date(-62135596800000)/变成日期
        formatArr:function (arr,format) {
            if(arr) {
                for (let value of arr) {
                   this.formatObj(value,format);
                }
            }
            return arr;
        },
        //转换成日期类型
        //输入格式：/Date(1234567900000)/
        parseToDate:function(strValue)
        {
            if(!strValue) return 0;
            if(strValue.length==0) return 0;
            var re = /^[0-9]+.?[0-9]*$/;
            var strInt = "";
            for(var i=0;i<strValue.length;i++)
            {
                if(re.test(strValue.charAt(i)))
                {
                    strInt += strValue.charAt(i);
                }
            }
            try{
                return new Date(parseInt(strInt));
            }catch(ex){
                return null;
            }
        },
        //日期转字符串
        //输出格式 pattern 如yyyy-MM-dd hh:mm:ss
        format: function (date, pattern) {
            if(!date){
                return ""
            }
            pattern = pattern || DEFAULT_PATTERN;
            return pattern.replace(SIGN_REGEXP, function ($0) {
                switch ($0.charAt(0)) {
                    case 'y': return padding(date.getFullYear(), $0.length);
                    case 'M': return padding(date.getMonth() + 1, $0.length);
                    case 'd': return padding(date.getDate(), $0.length);
                    case 'w': return date.getDay() + 1;
                    case 'h': return padding(date.getHours(), $0.length);
                    case 'm': return padding(date.getMinutes(), $0.length);
                    case 's': return padding(date.getSeconds(), $0.length);
                }
            });
        },
        //转换成日期类型
        //输入格式 pattern 如yyyy-MM-dd hh:mm:ss
        parse: function (dateString, pattern) {
            if(!dateString){
                return null
            }
            var matchs1 = pattern.match(SIGN_REGEXP);
            var matchs2 = dateString.match(/(\d)+/g);
            if (matchs1.length == matchs2.length) {
                var _date = new Date(1970, 0, 1);
                for (var i = 0; i < matchs1.length; i++) {
                    var _int = parseInt(matchs2[i]);
                    var sign = matchs1[i];
                    switch (sign.charAt(0)) {
                        case 'y': _date.setFullYear(_int); break;
                        case 'M': _date.setMonth(_int - 1); break;
                        case 'd': _date.setDate(_int); break;
                        case 'h': _date.setHours(_int); break;
                        case 'm': _date.setMinutes(_int); break;
                        case 's': _date.setSeconds(_int); break;
                    }
                }
                return _date;
            }
            return null;
        }

    }

};
